package cn.wolfcode.mq.linstener;

import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.SeckillProduct;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.redis.CommonRedisKey;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @Author: 普发忠
 * @Date: 2021/11/11/14:17
 */
@Component
@RocketMQMessageListener(
        topic = MQConstant.ORDER_PAY_TIMEOUT_TOPIC,
        consumerGroup = "order_pay_timeout_topic-consumer"
)
public class OrderPayListener implements RocketMQListener<OrderMQResult> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Override
    public void onMessage(OrderMQResult orderMessage) {
//        1)判断订单状态,是否是未支付
      OrderInfo orderInfo = orderInfoService.findOrderByOrderNo(orderMessage.getOrderNo());
        if (orderInfo!=null||orderInfo.getStatus()==OrderInfo.STATUS_ARREARAGE){
        
//        如果是未支付,就是超时失败.
//        2) 超时失败的逻辑
//                修改订单状态为超时失败
            orderInfoService.changeOrderStatus(orderInfo.getOrderNo(),OrderInfo.STATUS_TIMEOUT);
//        回补真实库存,真实库存+1
            seckillProductService.incrCountOne(orderMessage.getSeckillId());
//        同步预库存
            String bigkeystory = CommonRedisKey.SECKILL_PRODUCT_STORE.getRealKey(String.valueOf(orderMessage.getTime()));
            SeckillProduct seckillProduct = seckillProductService.findfromDB(orderMessage.getSeckillId());
            redisTemplate.opsForHash().put(bigkeystory, String.valueOf(orderMessage.getSeckillId()),
                    String.valueOf(seckillProduct.getStockCount()));
            //删除秒杀者
           rocketMQTemplate.syncSend(MQConstant.CANCEL_SECKILL_PERSION,orderMessage);
//        广播本地标识,修改为true.
            rocketMQTemplate.syncSend(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC,orderMessage.getSeckillId());
        }
        

    }
}
